package com.problem.leetcode;

/**
 * 解题思路:
 *1.设计两个指针 begin和end 前后遍历 如果将end对应的元素且不等于val的值 替换begin的值
 */
public class Problem27 {

    private int result = 0;

    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        result = nums.length;
        int begin = 0, end = nums.length - 1;
        while (begin < end) {
            if (nums[begin] == val) {
                int tmp = findNum(nums, begin, end, val);
                if (tmp != -1) {
                    nums[begin] = nums[tmp];
                    ++begin;
                    end = tmp - 1;
                    --result;
                } else {
                    return --result;
                }
            } else {
                ++begin;
            }
        }
        if (nums[begin] == val) {
            return --result;
        } else {
            return result;
        }
    }

    private int findNum(int[] nums, int begin, int end, int val) {
        while (begin < end) {
            if (nums[end] != val) {
                return end;
            } else {
                --result;
                --end;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {3,2,2, 3};
        new Problem27().removeElement(nums, 3);

        for (int index = 0; index < nums.length; index++) {
            System.out.println(nums[index]);
        }

    }


}
